﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using RadarMonitor.Converter;
using RadarMonitor.DB;

namespace RadarMonitor.Alarm
{
    /// <summary>
    /// 钉钉报警
    /// </summary>
    public class DingDingRobot
    {
        private static SourceCodeConverter sourceCodeConverter = new SourceCodeConverter();
        private static ResultCodeConverter resultCodeConverter = new ResultCodeConverter();
        public static void Alarm(RadarMonitorSource source, RadarMonitorResultCode code ,string msg)
        {
            if(RadarMonitor.Setting.Setting.GetConfig().DingDing.enable == false)
            {
                return;
            }
            try
            {
                IDingTalkClient client = new DefaultDingTalkClient(RadarMonitor.Setting.Setting.GetConfig().DingDing.Webhook);
                OapiRobotSendRequest req = new OapiRobotSendRequest();
                req.Msgtype = "markdown";
                string sourceStr = sourceCodeConverter.Convert(source, typeof(string), null, null) as string;
                string resultStr = resultCodeConverter.Convert(code, typeof(string), null, null) as string;
                string content = $"报警源：{sourceStr}; \n 报警类型：{resultStr}";
                if (msg != null)
                {
                    content += $";\n备注：{msg}";
                }
                var str = "{\"title\":\"监控报警\", \"text\":\"";
                str += content;
                str += "\"}";
                //var str = string.Format("{\"title\":\"监控报警\", \"text\":\"{0}\"}", content);
                req.Markdown = str;
                try
                {
                    OapiRobotSendResponse response = client.Execute(req);
                    Console.WriteLine($@"返回结果{response.Errcode}:{response.ErrMsg}");
                    if (response.Errcode != 0)
                    {
                        DBHelper.Instance.insertMonidorRow((int)RadarMonitorSource.App, (int)RadarMonitorResultCode.DingDingSendError, response.Errmsg);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

            }
            catch { }


        }
    }

}
